local extension = Package("ling6")
extension.extensionName = "lingling"

local U = require "packages/utility/utility"
local LUtil = require "packages/lingling/utility/ling_util"

local wuzhao = General(extension, "lingling__wuzhao", "tang", 3, 3, General.Female)
local dangguo = fk.CreateTriggerSkill{
  name = "lingling__dangguo",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.CardUseFinished},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and data.card.type == Card.TypeEquip then
      if player:usedSkillTimes(self.name, Player.HistoryRound) < 2 then
        return true
      elseif player:usedSkillTimes(self.name, Player.HistoryRound) < 4 then
        return not player:isNude()
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if player:usedSkillTimes(self.name, Player.HistoryRound) < 3 then
      player:drawCards(1, self.name)
    elseif player:usedSkillTimes(self.name, Player.HistoryRound) < 5 then
      local card = room:askForCard(player, 1, 1, true, self.name, false, nil, "#lingling__dangguo-recast")
      room:recastCard(card, player, self.name)
    end
    if table.contains({5, 9}, player:getHandcardNum()) and #room.alive_players > 0 then
      local luckyOne = table.random(room.alive_players)
      room:doIndicate(player.id, {luckyOne.id})
      luckyOne:drawCards(2, self.name)
      if not luckyOne.dead then
        luckyOne:turnOver()
      end
    end
  end,
}
local qiangzhong = fk.CreateTriggerSkill{
  name = "lingling__qiangzhong",
  anim_type = "offensive",
  events = {fk.TurnedOver, fk.ChainStateChanged},
  can_trigger = function (self, event, target, player, data)
    if not player:hasSkill(self) then return end
    if event == fk.TurnedOver then
      return not target.faceup and not target.dead
    else
      return target.chained and not target.dead
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local cid = room:askForDiscard(player, 1, 1, true, self.name, true, nil, "#lingling__qiangzhong-invoke::"..target.id, true)
    if #cid == 1 then
      self.cost_data = {tos = {target.id}, cards = cid}
      return true
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    room:throwCard(self.cost_data.cards, self.name, player, player)
    if not target.dead then
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
      }
    end
    --[[if player.dead or target.dead then return end
    local choice = room:askForChoice(player, {"lingling__qiangzhong_damage", "lingling__qiangzhong_draw"}, self.name,
      "#lingling__qiangzhong-choice::"..target.id)
    if choice == "lingling__qiangzhong_damage" then
      room:damage{
        from = player,
        to = target,
        damage = 1,
        skillName = self.name,
      }
    else
      target:drawCards(2, self.name)
    end]]--
  end,
}
local shenlong = fk.CreateTriggerSkill{
  name = "lingling__shenlong",
  mute = true,
  frequency = Skill.Compulsory,
  events = {fk.Damaged},
  can_trigger = function (self, event, target, player, data)
    return target == player and player:hasSkill(self)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    if #player:getCardIds("he") > 1 then
      room:notifySkillInvoked(player, self.name, "negative")
      if #room:askForDiscard(player, 2, 2, true, self.name, true, nil, "#lingling__shenlong-discard") < 2 then
        player:turnOver()
      end
    else
      room:notifySkillInvoked(player, self.name, "drawcard")
      player:drawCards(2, self.name)
    end
  end,
}
wuzhao:addSkill(dangguo)
wuzhao:addSkill(qiangzhong)
wuzhao:addSkill(shenlong)
Fk:loadTranslationTable{
  ["lingling__wuzhao"] = "武曌",
  ["#lingling__wuzhao"] = "天后",
  ["designer:lingling__wuzhao"] = "伶",
  ["illustrator:lingling__wuzhao"] = "珊瑚虫",

  ["lingling__dangguo"] = "荡国",
  [":lingling__dangguo"] = "每轮限四次，当一名角色使用装备牌后，你摸一张牌（每轮后两次改为重铸），然后若你手牌数为9或5，随机一名角色摸两张牌"..
  "并翻面。",
  ["lingling__qiangzhong"] = "戕忠",
  [":lingling__qiangzhong"] = "当一名角色翻至背面或横置后，你可以弃置一张牌并对其造成1点伤害。",
  ["lingling__shenlong"] = "神龙",
  [":lingling__shenlong"] = "当你受到伤害后，若你牌不少于两张，你弃置两张牌或翻面，若少于两张，你摸两张牌。"..
  "<br><br> <font color='#a40000'>圣母临朝，日月当空。</font>",
  ["#lingling__dangguo-recast"] = "荡国：请重铸一张牌",
  ["#lingling__qiangzhong-invoke"] = "戕忠：你可以弃置一张牌，对 %dest 造成1点伤害",
  --["#lingling__qiangzhong-choice"] = "戕忠：选择对 %dest 执行的一项",
  --["lingling__qiangzhong_damage"] = "对其造成1点伤害",
  --["lingling__qiangzhong_draw"] = "令其摸两张牌",
  ["#lingling__shenlong-discard"] = "神龙：你须弃置两张牌，或点“取消”翻面",
}

local fangxuanling = General(extension, "lingling__fangxuanling", "tang", 3)
local wenge = fk.CreateTriggerSkill{
  name = "lingling__wenge",
  anim_type = "drawcard",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Draw
  end,
  on_cost = function (self, event, target, player, data)
    local targets = player.room:getOtherPlayers(player)
    targets = table.map(targets, Util.IdMapper)
    local tos = player.room:askForChoosePlayers(player, targets, 1, 999, "#lingling__wenge-invoke", self.name, true)
    if #tos > 0 then
      self.cost_data = tos
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local tos = self.cost_data
    room:sortPlayersByAction(tos)
    player:drawCards(1, self.name)
    room:setPlayerMark(player, "@@lingling__wenge_mark-turn", 1)
    for _, id in ipairs(tos) do
      local to = room:getPlayerById(id)
      if not to.dead then
        to:drawCards(1, self.name)
        if not to.dead then
          room:setPlayerMark(to, "@@lingling__wenge_mark-turn", 1)
        end
      end
    end
    room.logic:getCurrentEvent():findParent(GameEvent.Turn):addCleaner(function()
      local tos = table.map(room.alive_players, Util.IdMapper)
      room:sortPlayersByAction(tos)
      for _, id in ipairs(tos) do
        local to = room:getPlayerById(id)
        if not to.dead and #to:getCardIds("h") == 3 then
          to:drawCards(1, self.name)
        end
      end
      for _, id in ipairs(tos) do
        local to = room:getPlayerById(id)
        if not to.dead and to.maxHp == 3 then
          to:drawCards(1, self.name)
        end
      end
    end)
    return true
  end,
}
local zhuanshi = fk.CreateTriggerSkill{
  name = "lingling__zhuanshi",
  anim_type = "drawcard",
  frequency = Skill.Limited,
  events = {fk.TurnEnd},
  can_trigger = function (self, event, target, player, data)
    return player:hasSkill(self) and target ~= player and player:usedSkillTimes(self.name, Player.HistoryGame) == 0 and
      table.find(player.room:getBanner("@$CenterArea"), function (id)
        return Fk:getCardById(id).type ~= Card.TypeBasic
      end)
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local cards = table.filter(room:getBanner("@$CenterArea"), function (id)
      return Fk:getCardById(id).type ~= Card.TypeBasic
    end)
    room:obtainCard(player, cards, true, fk.ReasonJustMove)
    if not player.dead and #cards > 3 then
      player:turnOver()
    end
  end,
}
Fk:loadTranslationTable{
  ["lingling__fangxuanling"] = "房玄龄",
  ["#lingling__fangxuanling"] = "房谋杜断",
  ["designer:lingling__fangxuanling"] = "伶",
  ["illustrator:lingling__fangxuanling"] = "伊达未来",

  ["lingling__wenge"] = "文阁",
  [":lingling__wenge"] = "摸牌阶段，你可以改为与任意名其他角色各摸一张牌，回合结束时，你们中手牌数为3的角色摸一张牌，体力上限为3的角色再摸一张牌。",
  ["#lingling__wenge-invoke"] = "文阁：你可以选择任意名其他角色，你与这些角色依次摸一张牌",
  ["@@lingling__wenge_mark-turn"] = "文阁",
  ["lingling__zhuanshi"] = "撰史",
  [":lingling__zhuanshi"] = "限定技，其他角色回合结束时，你可以获得中央区所有锦囊牌和装备牌，若你获得了至少四张牌，你翻面。"..
  "<br><br> <font color='#a40000'>辅相文皇功居第一，遗表之谏精忠贯日。</font>",

  ["$lingling__zhuanshi1"] = "古今明主盖以鉴古而隆运，而灵炀之流以戏史而废位。",
  ["$lingling__zhuanshi2"] = "千秋鸿毛，皆在笔下。",
}

local gaoxianzhi = General(extension, "lingling__gaoxianzhi", "tang", 4)
local xijin = fk.CreateActiveSkill{
  name = "lingling__xijin",
  anim_type = "control",
  min_card_num = 0,
  max_card_num = 1,
  min_target_num = 1,
  max_target_num = 2,
  prompt = "#lingling__xijin",
  times = function(self)
    return player.phase == Player.Play and 3 - player:usedSkillTimes(self.name, Player.HistoryTurn) or -1
  end,
  interaction = function(self)
    return UI.ComboBox { choices = {"lingling__xijin1", "lingling__xijin2", "lingling__xijin3"} }
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryTurn) < 3
  end,
  card_filter = function (self, player, to_select, selected)
    if self.interaction.data == "lingling__xijin1" then
      return false
    elseif self.interaction.data == "lingling__xijin2" then
      return #selected == 0
    elseif self.interaction.data == "lingling__xijin3" then
      return #selected == 0 and not player:prohibitDiscard(to_select)
    end
  end,
  target_filter = function(self, player, to_select, selected, selected_cards)
    if self.interaction.data == "lingling__xijin1" then
      if #selected == 0 then
        return true
      elseif #selected == 1 then
        local target1 = Fk:currentRoom():getPlayerById(selected[1])
        local target2 = Fk:currentRoom():getPlayerById(to_select)
        return target1:canMoveCardsInBoardTo(target2) or target2:canMoveCardsInBoardTo(target1)
      end
    elseif self.interaction.data == "lingling__xijin2" then
      return #selected == 0 and to_select ~= player.id
    elseif self.interaction.data == "lingling__xijin3" then
      return #selected == 0 and to_select ~= player.id and not Fk:currentRoom():getPlayerById(to_select):isKongcheng()
    end
  end,
  feasible = function (self,  player, selected, selected_cards)
    if self.interaction.data == "lingling__xijin1" then
      if #selected == 2 then
        local target1 = Fk:currentRoom():getPlayerById(selected[1])
        local target2 = Fk:currentRoom():getPlayerById(selected[2])
        return target1:canMoveCardsInBoardTo(target2) or target2:canMoveCardsInBoardTo(target1)
      end
    else
      return #selected == 1 and #selected_cards == 1
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    if self.interaction.data == "lingling__xijin1" then
      local targets = table.map(effect.tos, Util.Id2PlayerMapper)
      local result = room:askForMoveCardInBoard(player, targets[1], targets[2], self.name)
      if result then
        local target = room:getPlayerById(result.from)
        if #target:getCardIds("e") < #player:getCardIds("e") then
          local all_cards = table.simpleClone(room.draw_pile)
          table.insertTable(all_cards, table.simpleClone(room.discard_pile))
          local cards = table.filter(all_cards, function (id)
            local card = Fk:getCardById(id)
            return card.sub_type == result.card.sub_type and target:canUseTo(card, target)
          end)
          if #cards > 0 then
            room:useCard{
              from = target.id,
              tos = {{target.id}},
              card = Fk:getCardById(table.random(cards)),
            }
          end
        end
      end
    elseif self.interaction.data == "lingling__xijin2" then
      local target = room:getPlayerById(effect.tos[1])
      room:moveCardTo(effect.cards, Card.PlayerHand, target, fk.ReasonGive, self.name, nil, false, player.id)
      if target:isWounded() and not target.dead and target.hp < player.hp then
        room:recover{
          who = target,
          num = 1,
          recoverBy = player,
          skillName = self.name,
        }
      end
    elseif self.interaction.data == "lingling__xijin3" then
      local target = room:getPlayerById(effect.tos[1])
      room:throwCard(effect.cards, self.name, player, player)
      if player.dead or target.dead or target:isKongcheng() then return end
      local cards = U.askforChooseCardsAndChoice(player, target:getCardIds("h"), {"OK"}, self.name, "#lingling__xijin-prey::"..target.id)
      room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonPrey, self.name, nil, false, player.id)
      if not target.dead and target:getHandcardNum() < player:getHandcardNum() then
        target:drawCards(1, self.name)
      end
    end
  end,
}
local xijin_delay = fk.CreateTriggerSkill{
  name = "#lingling__xijin_delay",
  anim_type = "negative",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:usedSkillTimes("lingling__xijin", Player.HistoryPhase) > 0 and
      not table.find(player.room.alive_players, function (p)
        return #p:getCardIds("e") == 2 or p:getHandcardNum() == 2 or p.hp == 2
      end)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    player.room:killPlayer({who = player.id})
  end,
}
xijin:addRelatedSkill(xijin_delay)
gaoxianzhi:addSkill(xijin)
Fk:loadTranslationTable{
  ["lingling__gaoxianzhi"] = "高仙芝",
  ["#lingling__gaoxianzhi"] = "四海承平",
  ["designer:lingling__gaoxianzhi"] = "伶",
  ["illustrator:lingling__gaoxianzhi"] = "珊瑚虫",

  ["lingling__xijin"] = "西进",
  [":lingling__xijin"] = "出牌阶段，你可以执行一项，则本阶段结束时，若场上没有角色装备区牌数、或手牌数、或体力值为二，你死亡，每回合限三次：<br>"..
  "1.移动场上一张牌，然后若失去牌的角色装备区牌少于你，其随机使用一张同副类别的装备牌；<br>"..
  "2.交出一张牌，然后若获得牌的角色体力少于你，其回复1点体力；<br>"..
  "3.弃置一张牌，然后观看并获得一名其他角色一张手牌，然后若其手牌少于你，其摸一张牌。"..
  "<br><br> <font color='#a40000'>当我立在口顶闪光熠熠的积雪上向那直到六千英尺下雅新山谷尽头的峻坂下窥，对于起初拒绝向前移动后来"..
  "他们努力挣扎前进的高仙芝的勇敢，才能认识清楚。<br>——英国探险家马尔克·奥莱尔·斯坦因",
  ["#lingling__xijin"] = "西进：执行一项，本阶段结束时若没有角色装备数/手牌数/体力为2则死亡！",
  ["lingling__xijin1"] = "移动场上一张牌，若其装备少于你则其使用一张同副类别装备",
  ["lingling__xijin2"] = "交出一张牌，若其体力少于你则其回复1点体力",
  ["lingling__xijin3"] = "弃一张牌，观看并获得一名角色一张手牌，若其手牌少于你则其摸一张牌",
  ["#lingling__xijin-prey"] = "西进：获得 %dest 一张手牌",
  ["#lingling__xijin_delay"] = "西进",
}

local xuerengui = General(extension, "lingling__xuerengui", "tang", 4)
local chongzhen = fk.CreateTriggerSkill{
  name = "lingling__chongzhen",
  anim_type = "offensive",
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and
      table.find(player.room:getOtherPlayers(player), function (p)
        return not p:isKongcheng() or player:canUseTo(Fk:cloneCard("slash"), p, {bypass_times = true})
      end)
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    if table.find(player:getEquipments(Card.SubtypeWeapon), function (id)
      return Fk:getCardById(id).attack_range > 1
    end) then
      self.cost_data = nil
      return true
    end
    local success, dat = room:askForUseActiveSkill(player, "lingling__chongzhen_active", "#lingling__chongzhen-invoke", true, nil, false)
    if success and dat then
      self.cost_data = {tos = dat.targets, choice = dat.interaction}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if table.find(player:getEquipments(Card.SubtypeWeapon), function (id)
      return Fk:getCardById(id).attack_range > 1
    end) then
      local targets = table.filter(room:getOtherPlayers(player), function (p)
        return not p:isKongcheng()
      end)
      if #targets > 0 then
        local to = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1,
          "#lingling__chongzhen-choose", self.name, true)
        if #to > 0 then
          to = room:getPlayerById(to[1])
          local card = room:askForCardChosen(player, to, "h", self.name, "#lingling__chongzhen-prey::"..to.id)
          room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonPrey, self.name, nil, false, player.id)
          if player.dead then return end
        end
      end
      U.askForUseVirtualCard(room, player, "slash", nil, self.name, "#lingling__chongzhen-slash", true, true, false, true)
    else
      if self.cost_data.choice == "lingling__chongzhen1" then
        local to = room:getPlayerById(self.cost_data.tos[1])
        local card = room:askForCardChosen(player, to, "h", self.name, "#lingling__chongzhen-prey::"..to.id)
        room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonPrey, self.name, nil, false, player.id)
      else
        room:sortPlayersByAction(self.cost_data.tos)
        room:useVirtualCard("slash", nil, player, table.map(self.cost_data.tos, Util.Id2PlayerMapper), self.name, true)
      end
    end
  end,
}
local chongzhen_active = fk.CreateActiveSkill{
  name = "lingling__chongzhen_active",
  card_num = 0,
  min_target_num = 1,
  interaction = function ()
    return UI.ComboBox { choices = {"lingling__chongzhen1", "lingling__chongzhen2"} }
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards, _, _, player)
    if to_select == player.id then return end
    if self.interaction.data == "lingling__chongzhen1" then
      return #selected == 0 and not Fk:currentRoom():getPlayerById(to_select):isKongcheng()
    elseif self.interaction.data == "lingling__chongzhen2" then
      local card = Fk:cloneCard("slash")
      card.skillName = "lingling__chongzhen"
      return card.skill:targetFilter(to_select, selected, {}, card, {bypass_times = true}, player)
    end
  end,
  feasible = function (self, selected, selected_cards, player)
    if self.interaction.data == "lingling__chongzhen1" then
      return #selected == 1
    elseif self.interaction.data == "lingling__chongzhen2" then
      local card = Fk:cloneCard("slash")
      card.skillName = "lingling__chongzhen"
      return card.skill:feasible(selected, {}, player, card)
    end
  end,
}
local fengdan = fk.CreateTriggerSkill{
  name = "lingling__fengdan",
  mute = true,
  events = {fk.EventPhaseStart, fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(self) then
      if event == fk.EventPhaseStart then
        return player.phase == Player.Play and #player:getCardIds("he") > 1
      elseif event == fk.Damaged then
        return #player:getEquipments(Card.SubtypeWeapon) > 0
      end
    end
  end,
  on_cost = function(self, event, target, player, data)
    if event == fk.EventPhaseStart then
      local cards = player.room:askForDiscard(player, 2, 2, true, self.name, true, nil, "#lingling__fengdan-invoke", true)
      if #cards > 0 then
        self.cost_data = {cards = cards}
        return true
      end
    elseif event == fk.Damaged then
      self.cost_data = nil
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    player:broadcastSkillInvoke(self.name)
    if event == fk.EventPhaseStart then
      room:notifySkillInvoked(player, self.name, "drawcard")
      room:throwCard(self.cost_data.cards, self.name, player, player)
      if player.dead then return end
      local cards = room:getCardsFromPileByRule(".|.|.|.|.|weapon", 1, "allPiles")
      if #cards > 0 then
        room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
      end
    elseif event == fk.Damaged then
      room:notifySkillInvoked(player, self.name, "masochism")
      room:throwCard(player:getEquipments(Card.SubtypeWeapon), self.name, player, player)
      if player.dead then return end
      player:drawCards(2, self.name)
    end
  end,
}
local yingmeng = fk.CreateTriggerSkill{
  name = "lingling__yingmeng",
  anim_type = "support",
  frequency = Skill.Compulsory,
  events = {fk.RoundEnd},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and player.room:getBanner("RoundCount") == 1 and player.role ~= "lord"
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local lord = room:getLord() or room.alive_players[1]
    room:doIndicate(player.id, {lord.id})
    room:askForDiscard(lord, 2, 2, true, self.name, false)
    if not lord.dead then
      LUtil.GainRehearsalTurn(lord, self.name)
    end
    if not player.dead then
      LUtil.GainRehearsalTurn(player, self.name)
    end
  end,
}
Fk:loadTranslationTable{
  ["lingling__xuerengui"] = "薛仁贵",
  ["#lingling__xuerengui"] = "三军夺气",
  ["designer:lingling__xuerengui"] = "伶",
  ["illustrator:lingling__xuerengui"] = "伊达未来",

  ["lingling__chongzhen"] = "冲阵",
  [":lingling__chongzhen"] = "回合结束时，你可以选择一项：<br>1.获得一名其他角色一张手牌。<br>2.视为使用一张【杀】。<br>若你装备着攻击范围"..
  "大于2的武器牌，则改为依次执行两项。",
  ["lingling__fengdan"] = "锋胆",
  [":lingling__fengdan"] = "出牌阶段开始时，你可以弃置两张牌，然后随机获得一张武器牌。当你受到伤害后，若你装备着武器牌，你弃置之并摸两张牌。",
  ["lingling__yingmeng"] = "应梦",
  [":lingling__yingmeng"] = "第一轮结束时，若你不为主公，主公弃置两张牌，然后其与你依次执行一个<a href='ling_extra_turn'>预演回合</a>。"..
  "<br><br> <font color='#a40000'>弓一弯而天山未定，箭三发而铁勒知归。",
  ["lingling__chongzhen_active"] = "冲阵",
  ["#lingling__chongzhen-invoke"] = "冲阵：你可以选择一项",
  ["lingling__chongzhen1"] = "获得一名角色一张手牌",
  ["lingling__chongzhen2"] = "视为使用一张【杀】",
  ["#lingling__chongzhen-prey"] = "冲阵：获得 %dest 一张手牌",
  ["#lingling__chongzhen-choose"] = "冲阵：你可以获得一名角色一张手牌",
  ["#lingling__chongzhen-slash"] = "冲阵：你可以视为使用一张【杀】",
  ["#lingling__fengdan-invoke"] = "锋胆：你可以弃置两张牌，随机获得一张武器牌",
}

local duruhui = General(extension, "lingling__duruhui", "tang", 3)
local mouduan = fk.CreateViewAsSkill{
  name = "lingling__mouduan",
  anim_type = "control",
  pattern = "nullification",
  prompt = "#lingling__mouduan",
  times = function(self)
    return 3 + player:getMark(self.name) - player:usedSkillTimes(self.name, Player.HistoryGame)
  end,
  card_filter = Util.FalseFunc,
  view_as = function(self, player, cards)
    local card = Fk:cloneCard("nullification")
    card.skillName = self.name
    return card
  end,
  before_use = function (self, player, use)
    use.disresponsiveList = table.map(player.room.players, Util.IdMapper)
  end,
  enabled_at_response = function (self, player, response)
    return not response and player:usedSkillTimes(self.name, Player.HistoryGame) < 3 + player:getMark(self.name)
  end,
}
local mouduan_delay = fk.CreateTriggerSkill{
  name = "#lingling__mouduan_delay",

  refresh_events = {fk.Damaged},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(mouduan, true)
  end,
  on_refresh = function(self, event, target, player, data)
    player.room:addPlayerMark(player, "lingling__mouduan", 1)
  end,
}
local zhangcai = fk.CreateActiveSkill{
  name = "lingling__zhangcai",
  anim_type = "control",
  card_num = 0,
  min_target_num = 1,
  max_target_num = 2,
  prompt = "#lingling__zhangcai",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, player, to_select, selected)
    if #selected < 2 then
      if to_select == player.id then
        return #table.filter(player:getCardIds("he"), function (id)
          return not player:prohibitDiscard(id)
        end) > 1
      else
        return #Fk:currentRoom():getPlayerById(to_select):getCardIds("he") > 1
      end
    end
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    room:sortPlayersByAction(effect.tos)
    for _, id in ipairs(effect.tos) do
      local p = room:getPlayerById(id)
      if not p.dead and not p:isNude() then
        room:askForDiscard(p, 2, 2, true, self.name, false)
      end
    end
    for _, id in ipairs(effect.tos) do
      local p = room:getPlayerById(id)
      if not p.dead then
        local cards = room:getCardsFromPileByRule(".|.|.|.|.|trick", 1, "allPiles")
        if #cards > 0 then
          room:moveCardTo(cards, Card.PlayerHand, p, fk.ReasonJustMove, "lingling__zhangcai", nil, false, p.id)
          if p ~= player and table.contains(p:getCardIds("h"), cards[1]) and not player.dead then
            room:setCardMark(Fk:getCardById(cards[1]), "@@lingling__zhangcai-inhand", player.id)
          end
        end
      end
    end
  end,
}
local zhangcai_delay = fk.CreateTriggerSkill{
  name = "#lingling__zhangcai_delay",
  anim_type = "drawcard",
  events = {fk.CardUseFinished},
  can_trigger = function (self, event, target, player, data)
    return data.extra_data and data.extra_data.lingling__zhangcai == player.id and not player.dead and
      player.room:getCardArea(data.card) == Card.Processing
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    player.room:moveCardTo(data.card, Card.PlayerHand, player, fk.ReasonPrey, "lingling__zhangcai", nil, true, player.id)
  end,

  refresh_events = {fk.PreCardUse},
  can_refresh = function (self, event, target, player, data)
    return target == player and data.card:getMark("@@lingling__zhangcai-inhand") ~= 0
  end,
  on_refresh = function (self, event, target, player, data)
    data.extra_data = data.extra_data or {}
    data.extra_data.lingling__zhangcai = data.card:getMark("@@lingling__zhangcai-inhand")
  end,
}
mouduan:addRelatedSkill(mouduan_delay)
zhangcai:addRelatedSkill(zhangcai_delay)
duruhui:addSkill(mouduan)
duruhui:addSkill(zhangcai)
Fk:loadTranslationTable{
  ["lingling__duruhui"] = "杜如晦",
  ["#lingling__duruhui"] = "德宣内外",
  ["designer:lingling__duruhui"] = "伶",
  ["illustrator:lingling__duruhui"] = "珊瑚虫",

  ["lingling__mouduan"] = "谋断",
  [":lingling__mouduan"] = "每局限三次，你可以视为使用一张无法被【无懈可击】抵消的【无懈可击】。当你受到1点伤害后，此技能限次加一。",
  ["lingling__zhangcai"] = "彰才",
  [":lingling__zhangcai"] = "出牌阶段限一次，你可以令至多两名角色各弃置两张牌，然后各随机获得一张锦囊牌。这些角色中的其他角色使用以此法"..
  "获得锦囊牌后你获得之。"..
  "<br><br> <font color='#a40000'>建平文雅，休有烈光。<br>怀忠履义，身立名扬。",
  ["#lingling__mouduan"] = "谋断：你可以视为使用【无懈可击】",
  ["#lingling__zhangcai"] = "彰才：令至多两名角色各弃置两张牌并各随机获得一张锦囊牌，其他角色使用这些锦囊牌后你获得之",
  ["@@lingling__zhangcai-inhand"] = "彰才",
  ["#lingling__zhangcai_delay"] = "彰才",
}

local songzain_gambo = General(extension, "lingling__songzain_gambo", "qun", 4)
local siru = fk.CreateActiveSkill{
  name = "lingling__siru",
  anim_type = "control",
  card_num = 2,
  target_num = 1,
  prompt = "#lingling__siru",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = function(self, player, to_select, selected)
    return #selected < 2
  end,
  target_filter = function(self, player, to_select, selected)
    return #selected == 0 and to_select ~= player.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:moveCardTo(effect.cards, Card.PlayerHand, target, fk.ReasonGive, self.name, nil, false, player.id)
    if target.dead then return end
    local use = room:askForUseCard(target, self.name, "slash", "#lingling__siru-slash", true, {bypass_times = true})
    if use then
      use.extraUse = true
      room:useCard(use)
    else
      room:loseHp(target, 1, self.name)
    end
    if player.dead or target.dead then return end
    local mark = target:getTableMark(self.name)
    table.insertIfNeed(mark, player.id)
    room:setPlayerMark(target, self.name, mark)
  end,
}
local siru_delay = fk.CreateTriggerSkill{
  name = "#lingling__siru_delay",
  anim_type = "control",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    return target.phase == Player.Play and table.contains(target:getTableMark("lingling__siru"), player.id)
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:removeTableMark(target, "lingling__siru", player.id)
    if player.dead or target:isNude() then return end
    local n = 1 + #room.logic:getEventsOfScope(GameEvent.UseCard, 999, function (e)
      local use = e.data[1]
      return use.from == target.id and table.contains({"peach", "analeptic"}, use.card.trueName)
    end, Player.HistoryGame)
    room:doIndicate(player.id, {target.id})
    local cards = target:getCardIds("he")
    if #cards > n then
      cards = room:askForCard(target, n, n, true, "lingling__siru", false, nil, "#lingling__siru-give:"..player.id.."::"..n)
    end
    room:moveCardTo(cards, Card.PlayerHand, player, fk.ReasonGive, "lingling__siru", nil, false, target.id)
  end,
}
local resa = fk.CreateTriggerSkill{
  name = "lingling__resa",
  anim_type = "special",
  frequency = Skill.Compulsory,
  events = {fk.DamageCaused},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and data.to:isKongcheng() and
      ((target == player and data.to ~= player) or (target ~= player and data.to == player))
  end,
  on_use = function(self, event, target, player, data)
    data.to:drawCards(3, self.name)
  end,
}
local nima = fk.CreateActiveSkill{
  name = "lingling__nima",
  anim_type = "control",
  card_num = 0,
  target_num = 1,
  prompt = "#lingling__nima",
  interaction = function(self)
    return UI.CardNameBox { choices = {"peach", "analeptic"} }
  end,
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected, selected_cards)
    return #selected == 0 and to_select ~= player.id
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    room:useVirtualCard(self.interaction.data, nil, player, player, self.name)
    if not target.dead then
      local name = self.interaction.data == "peach" and "analeptic" or "peach"
      room:useVirtualCard(name, nil, target, target, self.name)
    end
    room:swapSeat(player, target)
  end,
}
siru:addRelatedSkill(siru_delay)
songzain_gambo:addSkill(siru)
songzain_gambo:addSkill(resa)
songzain_gambo:addSkill(nima)
Fk:loadTranslationTable{
  ["lingling__songzain_gambo"] = "松赞干布",
  ["#lingling__songzain_gambo"] = "真观远视",
  ["designer:lingling__songzain_gambo"] = "伶",
  ["illustrator:lingling__songzain_gambo"] = "",

  ["lingling__siru"] = "四茹",
  [":lingling__siru"] = "出牌阶段限一次，你可以交给一名其他角色两张牌，其使用【杀】或失去1点体力，且其下个出牌阶段结束时交给你X张牌"..
  "（X为其本局使用【桃】和【酒】的总数+1）。",
  ["lingling__resa"] = "惹萨",
  [":lingling__resa"] = "当你对其他角色造成伤害时，若其没有手牌，其摸三张牌。当其他角色对你造成伤害时，若你没有手牌，你摸三张牌。",
  ["lingling__nima"] = "尼玛",
  [":lingling__nima"] = "限定技，出牌阶段，你可以选择一名其他角色，你视为使用【桃】或【酒】，其视为使用另一种，然后你们交换位置。"..
  "<br><br> <font color='#a40000'>举凡吐蕃之一切纯良风俗，贤明政事，均为此墀松赞王者之时出现也。",
  ["#lingling__siru"] = "四茹：交给一名角色两张牌，其选择使用【杀】或失去1点体力，且其出牌阶段结束时交给你牌",
  ["#lingling__siru-slash"] = "四茹：使用一张【杀】，或点“取消”失去1点体力",
  ["#lingling__siru_delay"] = "四茹",
  ["#lingling__siru-give"] = "四茹：请交给 %src %arg张牌",
  ["#lingling__nima"] = "尼玛：选择一名角色，你与其分别视为使用【桃】或【酒】，然后与其交换位置",
}

return extension
